package top.system.dept.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;

/**
 *
 * 因为微信小程序现在的消息类型只支持一次性消息订阅，不满足随时下发业务通知的需求
 * 因此这里使用邮件下发的方式下发通知
 *
 * @ClassName: MailService
 * @Author: Amosen
 * @Since: 2021/5/29
 */

// 邮件发送服务类，实现通知的下发
@Service
public class MailService {

    private Logger logger = LoggerFactory.getLogger(MailService.class);

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String sendFrom;

    public void sendMail(String subject, String toUser, Map<String, Object> contextDatas, String templateName) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject(subject);
            helper.setFrom(sendFrom);
            helper.setTo(toUser);
            helper.setSentDate(new Date());
            Context context = new Context();
            for (Map.Entry<String, Object> contextData : contextDatas.entrySet()) {
                context.setVariable(contextData.getKey(), contextData.getValue());
            }
            String process = templateEngine.process(templateName, context);
            helper.setText(process, true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("Send e-mail to <" + toUser + "> failed", e);
        }
    }

}
